import pool from '../config/database';

// 游戏接口
export interface Game {
  id: number;
  name: string;
  max_players: number;
  min_bet: number;
  small_blind: number;
  big_blind: number;
  buy_in: number;
  current_players: number;
  status: 'waiting' | 'in-progress' | 'finished';
  created_by: number;
  created_at: Date;
  updated_at: Date;
  // 游戏状态相关属性
  players?: GamePlayer[];
  currentPlayerPosition?: number;
  currentBet?: number;
  pot?: number;
  sidePot?: number;
  communityCards?: string[];
  deck?: string[];
  phase?: GamePhase;
}

// 游戏玩家接口
export interface GamePlayer {
  id: number;
  game_id: number;
  user_id: number;
  position: number;
  chips: number;
  cards: string[];
  status: 'active' | 'folded' | 'all-in';
  bet: number;
  currentBet?: number;
  hasFolded?: boolean;
  isAllIn?: boolean;
  joined_at: Date;
}

// 游戏阶段枚举
export enum GamePhase {
  WAITING = 'waiting',
  PREFLOP = 'preflop',
  FLOP = 'flop',
  TURN = 'turn',
  RIVER = 'river',
  SHOWDOWN = 'showdown',
  FINISHED = 'finished'
}

// 游戏状态接口
export interface GameState {
  id: number;
  game_id: number;
  phase: GamePhase;
  pot: number;
  current_bet: number;
  current_player_position: number;
  community_cards: string[];
  deck: string[];
  side_pot?: number;
  created_at: Date;
  updated_at: Date;
}

// 创建游戏表
export const createGameTable = async (): Promise<void> => {
  const query = `
    CREATE TABLE IF NOT EXISTS games (
      id SERIAL PRIMARY KEY,
      name VARCHAR(100) NOT NULL,
      max_players INTEGER NOT NULL DEFAULT 6,
      min_bet INTEGER NOT NULL DEFAULT 10,
      small_blind INTEGER NOT NULL DEFAULT 5,
      big_blind INTEGER NOT NULL DEFAULT 10,
      buy_in INTEGER NOT NULL DEFAULT 1000,
      current_players INTEGER NOT NULL DEFAULT 0,
      status VARCHAR(20) NOT NULL DEFAULT 'waiting',
      created_by INTEGER NOT NULL REFERENCES users(id),
      created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
      updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )
  `;
  
  try {
    await db.query(query);
    console.log('Games table created successfully');
  } catch (error) {
    console.error('Error creating games table:', error);
    throw error;
  }
};

// 创建游戏玩家表
export const createGamePlayerTable = async (): Promise<void> => {
  const query = `
    CREATE TABLE IF NOT EXISTS game_players (
      id SERIAL PRIMARY KEY,
      game_id INTEGER NOT NULL REFERENCES games(id),
      user_id INTEGER NOT NULL REFERENCES users(id),
      position INTEGER NOT NULL,
      chips INTEGER NOT NULL DEFAULT 1000,
      cards TEXT[] DEFAULT '{}',
      status VARCHAR(20) NOT NULL DEFAULT 'active',
      bet INTEGER NOT NULL DEFAULT 0,
      is_active BOOLEAN NOT NULL DEFAULT true,
      joined_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
      UNIQUE(game_id, user_id)
    )
  `;
  
  try {
    await pool.query(query);
    console.log('Game players table created successfully');
  } catch (error) {
    console.error('Error creating game players table:', error);
    throw error;
  }
};

// 创建游戏状态表
export const createGameStateTable = async (): Promise<void> => {
  const query = `
    CREATE TABLE IF NOT EXISTS game_state (
      id SERIAL PRIMARY KEY,
      game_id INTEGER NOT NULL REFERENCES games(id),
      phase VARCHAR(20) NOT NULL DEFAULT 'waiting',
      pot INTEGER NOT NULL DEFAULT 0,
      current_bet INTEGER NOT NULL DEFAULT 0,
      current_player_position INTEGER NOT NULL DEFAULT 0,
      community_cards TEXT[] DEFAULT '{}',
      deck TEXT[] DEFAULT '{}',
      side_pot INTEGER DEFAULT 0,
      created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
      updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )
  `;
  
  try {
    await pool.query(query);
    console.log('Game states table created successfully');
  } catch (error) {
    console.error('Error creating game states table:', error);
    throw error;
  }
};

// 获取所有游戏列表
export const getAllGames = async (): Promise<Game[]> => {
  try {
    const result = await pool.query('SELECT * FROM games ORDER BY created_at DESC');
    return result.rows;
  } catch (error) {
    console.error('Error getting all games:', error);
    throw error;
  }
};

// 获取游戏列表（带状态过滤和分页）
export const getGames = async (status?: string, limit = 10, offset = 0): Promise<Game[]> => {
  try {
    let query = 'SELECT * FROM games';
    const params: any[] = [];
    
    if (status) {
      query += ' WHERE status = $1';
      params.push(status);
    }
    
    query += ' ORDER BY created_at DESC LIMIT $' + (params.length + 1) + ' OFFSET $' + (params.length + 2);
    params.push(limit, offset);
    
    const result = await pool.query(query, params);
    return result.rows;
  } catch (error) {
    console.error('获取游戏列表错误:', error);
    throw error;
  }
};

// 根据ID获取游戏
export const getGameById = async (id: number): Promise<Game | null> => {
  try {
    const result = await pool.query('SELECT * FROM games WHERE id = $1', [id]);
    return result.rows.length > 0 ? result.rows[0] : null;
  } catch (error) {
    console.error('Error getting game by ID:', error);
    throw error;
  }
};

// 更新游戏
export const updateGame = async (gameId: number, updates: Partial<Game>): Promise<Game | null> => {
  try {
    const fields = Object.keys(updates);
    if (fields.length === 0) return null;

    const setClause = fields.map((field, i) => `${field} = $${i + 2}`).join(', ');
    const values = fields.map(f => (updates as any)[f]);
    
    const query = `
      UPDATE games
      SET ${setClause}, updated_at = CURRENT_TIMESTAMP
      WHERE id = $1
      RETURNING *
    `;
    
    const result = await pool.query(query, [gameId, ...values]);
    return result.rows.length > 0 ? result.rows[0] : null;
  } catch (error) {
    console.error('Error updating game:', error);
    throw error;
  }
};

// 创建新游戏
export const createGame = async (name: string, createdBy: number, maxPlayers: number, smallBlind: number, bigBlind: number, buyIn: number): Promise<Game> => {
  try {
    const query = `
      INSERT INTO games (name, created_by, max_players, small_blind, big_blind, buy_in)
      VALUES ($1, $2, $3, $4, $5, $6)
      RETURNING *
    `;
    
    const result = await pool.query(query, [name, createdBy, maxPlayers, smallBlind, bigBlind, buyIn]);
    return result.rows[0];
  } catch (error) {
    console.error('创建游戏错误:', error);
    throw error;
  }
};

// 更新游戏状态
export const updateGameStatus = async (id: number, status: Game['status']): Promise<Game | null> => {
  try {
    const query = `
      UPDATE games
      SET status = $1, updated_at = CURRENT_TIMESTAMP
      WHERE id = $2
      RETURNING *
    `;
    
    const result = await pool.query(query, [status, id]);
    return result.rows.length > 0 ? result.rows[0] : null;
  } catch (error) {
    console.error('Error updating game status:', error);
    throw error;
  }
};

// 增加游戏玩家数
export const incrementGamePlayers = async (gameId: number): Promise<Game | null> => {
  try {
    const updateQuery = `
      UPDATE games 
      SET current_players = current_players + 1 
      WHERE id = $1
      RETURNING *
    `;
    const result = await pool.query(updateQuery, [gameId]);
    return result.rows[0] || null;
  } catch (error) {
    console.error('增加游戏玩家数错误:', error);
    return null;
  }
};

// 减少游戏玩家数
export const decrementGamePlayers = async (gameId: number): Promise<Game | null> => {
  try {
    const updateQuery = `
      UPDATE games 
      SET current_players = current_players - 1 
      WHERE id = $1 AND current_players > 0
      RETURNING *
    `;
    const result = await pool.query(updateQuery, [gameId]);
    return result.rows[0] || null;
  } catch (error) {
    console.error('减少游戏玩家数错误:', error);
    return null;
  }
};

// 添加玩家到游戏
export const addPlayerToGame = async (gameId: number, userId: number, position: number, chips: number): Promise<boolean> => {
  try {
    const insertQuery = `
      INSERT INTO game_players (game_id, user_id, position, chips, is_active)
      VALUES ($1, $2, $3, $4, true)
      RETURNING *
    `;
    await pool.query(insertQuery, [gameId, userId, position, chips]);
    return true;
  } catch (error) {
    console.error('添加玩家到游戏错误:', error);
    return false;
  }
};

// 从游戏中移除玩家
export const removePlayerFromGame = async (gameId: number, userId: number): Promise<boolean> => {
  try {
    const deleteQuery = `
      DELETE FROM game_players 
      WHERE game_id = $1 AND user_id = $2
      RETURNING *
    `;
    await pool.query(deleteQuery, [gameId, userId]);
    return true;
  } catch (error) {
    console.error('从游戏中移除玩家错误:', error);
    return false;
  }
};

// 创建游戏状态
export const createGameState = async (gameId: number, phase: GamePhase, deck: string[]): Promise<boolean> => {
  try {
    const insertQuery = `
      INSERT INTO game_state (game_id, phase, deck)
      VALUES ($1, $2, $3)
      RETURNING *
    `;
    await pool.query(insertQuery, [gameId, phase, JSON.stringify(deck)]);
    return true;
  } catch (error) {
    console.error('创建游戏状态错误:', error);
    return false;
  }
};

// 更新游戏状态
export const updateGameStatus = async (gameId: number, status: string): Promise<Game | null> => {
  try {
    const updateQuery = `
      UPDATE games 
      SET status = $1, updated_at = CURRENT_TIMESTAMP
      WHERE id = $2
      RETURNING *
    `;
    const result = await pool.query(updateQuery, [status, gameId]);
    return result.rows[0] || null;
  } catch (error) {
    console.error('更新游戏状态错误:', error);
    return null;
  }
};

// 获取游戏中的所有玩家
export const getGamePlayers = async (gameId: number): Promise<GamePlayer[]> => {
  try {
    const query = `
      SELECT gp.*, u.username, u.email
      FROM game_players gp
      JOIN users u ON gp.user_id = u.id
      WHERE gp.game_id = $1
      ORDER BY gp.position
    `;
    
    const result = await pool.query(query, [gameId]);
    return result.rows;
  } catch (error) {
    console.error('Error getting game players:', error);
    throw error;
  }
};

// 添加玩家到游戏
export const addPlayerToGame = async (gameId: number, userId: number, position: number, chips: number): Promise<GamePlayer> => {
  try {
    const query = `
      INSERT INTO game_players (game_id, user_id, position, chips)
      VALUES ($1, $2, $3, $4)
      RETURNING *
    `;
    
    const result = await pool.query(query, [gameId, userId, position, chips]);
    return result.rows[0];
  } catch (error) {
    console.error('Error adding player to game:', error);
    throw error;
  }
};

// 从游戏中移除玩家
export const removePlayerFromGame = async (gameId: number, userId: number): Promise<boolean> => {
  try {
    const result = await pool.query('DELETE FROM game_players WHERE game_id = $1 AND user_id = $2', [gameId, userId]);
    return result.rowCount > 0;
  } catch (error) {
    console.error('Error removing player from game:', error);
    throw error;
  }
};

// 获取游戏状态
export const getGameState = async (gameId: number): Promise<GameState | null> => {
  try {
    const result = await pool.query('SELECT * FROM game_states WHERE game_id = $1', [gameId]);
    return result.rows.length > 0 ? result.rows[0] : null;
  } catch (error) {
    console.error('Error getting game state:', error);
    throw error;
  }
};

// 创建游戏状态
export const createGameState = async (gameId: number, phase: GamePhase, deck: string[]): Promise<GameState> => {
  try {
    const query = `
      INSERT INTO game_states (game_id, phase, deck)
      VALUES ($1, $2, $3)
      RETURNING *
    `;
    
    const result = await pool.query(query, [gameId, phase, deck]);
    return result.rows[0];
  } catch (error) {
    console.error('Error creating game state:', error);
    throw error;
  }
};

// 更新游戏状态
export const updateGameState = async (
  gameId: number,
  phase: GamePhase,
  pot: number,
  currentBet: number,
  currentPlayerPosition: number,
  communityCards: string[],
  deck: string[],
  sidePot?: number
): Promise<GameState | null> => {
  try {
    const query = `
      UPDATE game_states
      SET phase = $1, pot = $2, current_bet = $3, current_player_position = $4,
          community_cards = $5, deck = $6, side_pot = $7, updated_at = CURRENT_TIMESTAMP
      WHERE game_id = $8
      RETURNING *
    `;
    
    const result = await pool.query(query, [
      phase, pot, currentBet, currentPlayerPosition, communityCards, deck, sidePot || 0, gameId
    ]);
    return result.rows.length > 0 ? result.rows[0] : null;
  } catch (error) {
    console.error('Error updating game state:', error);
    throw error;
  }
};

// 更新玩家筹码
export const updatePlayerChips = async (gameId: number, userId: number, chips: number): Promise<{ success: boolean; game?: Game; message?: string }> => {
  try {
    // 获取游戏状态
    const gameState = await getGameState(gameId);
    if (!gameState) {
      return { success: false, message: '游戏状态不存在' };
    }
    
    // 获取玩家信息
    const gamePlayers = await getGamePlayers(gameId);
    const player = gamePlayers.find(p => p.user_id === userId);
    if (!player) {
      return { success: false, message: '玩家不在游戏中' };
    }
    
    // 更新玩家筹码
    const query = `
      UPDATE game_players
      SET chips = $1, updated_at = CURRENT_TIMESTAMP
      WHERE game_id = $2 AND user_id = $3
      RETURNING *
    `;
    
    const result = await pool.query(query, [chips, gameId, userId]);
    if (result.rows.length === 0) {
      return { success: false, message: '更新玩家筹码失败' };
    }
    
    // 获取更新后的游戏信息
    const updatedGame = await getGameById(gameId);
    if (!updatedGame) {
      return { success: false, message: '获取游戏信息失败' };
    }
    
    return { success: true, game: updatedGame };
  } catch (error) {
    console.error('更新玩家筹码错误:', error);
    return { success: false, message: '更新玩家筹码失败' };
  }
};

// 加入游戏
export const joinGame = async (gameId: number, userId: number): Promise<{ success: boolean; game?: Game; message?: string }> => {
  try {
    // 获取游戏信息
    const game = await getGameById(gameId);
    if (!game) {
      return { success: false, message: '游戏不存在' };
    }
    
    // 检查游戏状态
    if (game.status !== 'waiting') {
      return { success: false, message: '游戏已开始，无法加入' };
    }
    
    // 检查玩家数量
    if (game.current_players >= game.max_players) {
      return { success: false, message: '游戏已满员' };
    }
    
    // 检查玩家是否已在游戏中
    const gamePlayers = await getGamePlayers(gameId);
    if (gamePlayers.some(p => p.user_id === userId)) {
      return { success: false, message: '您已在此游戏中' };
    }
    
    // 添加玩家到游戏
    const position = gamePlayers.length; // 使用当前玩家数作为位置
    const defaultChips = 1000; // 默认筹码
    await addPlayerToGame(gameId, userId, position, defaultChips);
    
    // 更新游戏玩家数
    const updatedGame = await incrementGamePlayers(gameId);
    if (!updatedGame) {
      return { success: false, message: '更新游戏信息失败' };
    }
    
    return { success: true, game: updatedGame };
  } catch (error) {
    console.error('加入游戏错误:', error);
    return { success: false, message: '加入游戏失败' };
  }
};

// 离开游戏
export const leaveGame = async (gameId: number, userId: number): Promise<{ success: boolean; game?: Game; message?: string }> => {
  try {
    // 获取游戏信息
    const game = await getGameById(gameId);
    if (!game) {
      return { success: false, message: '游戏不存在' };
    }
    
    // 检查玩家是否在游戏中
    const gamePlayers = await getGamePlayers(gameId);
    const player = gamePlayers.find(p => p.user_id === userId);
    if (!player) {
      return { success: false, message: '您不在此游戏中' };
    }
    
    // 检查游戏状态
    if (game.status === 'in-progress') {
      return { success: false, message: '游戏进行中，无法离开' };
    }
    
    // 从游戏中移除玩家
    const removed = await removePlayerFromGame(gameId, userId);
    if (!removed) {
      return { success: false, message: '离开游戏失败' };
    }
    
    // 更新游戏玩家数
    const updatedGame = await decrementGamePlayers(gameId);
    if (!updatedGame) {
      return { success: false, message: '更新游戏信息失败' };
    }
    
    return { success: true, game: updatedGame };
  } catch (error) {
    console.error('离开游戏错误:', error);
    return { success: false, message: '离开游戏失败' };
  }
};

// 开始游戏
export const startGame = async (gameId: number, userId: number): Promise<{ success: boolean; game?: Game; message?: string }> => {
  try {
    // 获取游戏信息
    const game = await getGameById(gameId);
    if (!game) {
      return { success: false, message: '游戏不存在' };
    }
    
    // 检查是否是游戏创建者
    if (game.created_by !== userId) {
      return { success: false, message: '只有游戏创建者可以开始游戏' };
    }
    
    // 检查游戏状态
    if (game.status !== 'waiting') {
      return { success: false, message: '游戏已开始或已结束' };
    }
    
    // 检查玩家数量
    if (game.current_players < 2) {
      return { success: false, message: '至少需要2名玩家才能开始游戏' };
    }
    
    // 创建游戏状态
    const deck = createDeck(); // 创建一副牌
    await createGameState(gameId, GamePhase.PREFLOP, deck);
    
    // 更新游戏状态
    const updatedGame = await updateGameStatus(gameId, 'in-progress');
    if (!updatedGame) {
      return { success: false, message: '更新游戏状态失败' };
    }
    
    return { success: true, game: updatedGame };
  } catch (error) {
    console.error('开始游戏错误:', error);
    return { success: false, message: '开始游戏失败' };
  }
};

// 创建一副牌
const createDeck = (): string[] => {
  const suits = ['♠', '♥', '♦', '♣'];
  const ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'];
  const deck: string[] = [];
  
  for (const suit of suits) {
    for (const rank of ranks) {
      deck.push(`${rank}${suit}`);
    }
  }
  
  // 洗牌
  for (let i = deck.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [deck[i], deck[j]] = [deck[j], deck[i]];
  }
  
  return deck;
};